﻿using System;
using System.Net;
using System.Windows;

namespace Automator.Runtime.Wizards
{
    /// <summary>
    /// Interaction logic for ProxyWizard.xaml
    /// </summary>
    public partial class ProxyWizard : Window
    {
        private WebProxy proxy = new WebProxy();
        public WebProxy Result
        {
            get { return (String.IsNullOrEmpty(proxy.Address.Host)) ? null : proxy; }
        }
        
        public ProxyWizard()
        {
            InitializeComponent();
            
            wizard.Cancelled += delegate { this.DialogResult = false; Close(); };
            wizard.Finished += new RoutedEventHandler(wizard_Finished);
            wizard.Finished += delegate { this.DialogResult = true; Close(); };
            ChkAuth_Click(null, new RoutedEventArgs());            
        }

        private void wizard_Finished(object sender, RoutedEventArgs e)
        {
            proxy = new WebProxy(edtHost.Text, Convert.ToInt32(edtPort.Text));
            proxy.BypassProxyOnLocal = chkBypass.IsChecked.Value;
                if (chkAuth.IsChecked.Value)
                    proxy.Credentials = new NetworkCredential(edtUsername.Text, edtPassword.Password);
        }
        
        public ProxyWizard(WebProxy value): this()
        {
            if (value != null)
            {
                edtHost.Text = value.Address.Host;
                edtPort.Text = value.Address.Port.ToString();
                chkBypass.IsChecked = value.BypassProxyOnLocal;
                if (value.Credentials != null)
                {
                    NetworkCredential credential = value.Credentials.GetCredential(new Uri("http://www.ru"), "Basic");
                    if (credential != null)
                    {
                        chkAuth.IsChecked = true;
                        ChkAuth_Click(null, new RoutedEventArgs());
                        edtUsername.Text = credential.UserName;
                        edtPassword.Password = credential.Password;
                    }
                }
            }
        }
        
        private void ChkAuth_Click(object sender, RoutedEventArgs e)
        {
            edtUsername.IsEnabled = chkAuth.IsChecked.Value;
            edtPassword.IsEnabled = chkAuth.IsChecked.Value;
        }
        
        private void BtnDefaultProxy_Click(object sender, RoutedEventArgs e)
        {
            Uri proxy = HttpWebRequest.GetSystemWebProxy().GetProxy(new Uri("http://www.ru"));
            edtHost.Text = proxy.Host;
            edtPort.Text = proxy.Port.ToString();
        }        
    }
}